package goinput

import (
	"bytes"
	"fmt"

	"notabug.org/_percival/goinput/maps"
)

// Key combinations to trigger events.
type Keys map[string]*Key

// Clear all key.Code and return keys.
func (keys Keys) Clear() Keys {
	for _, key := range keys {
		key.Code = [][]byte{}
	}

	return keys
}

// Compile keys according to their names if key.Code is empty.
func (keys Keys) Compile() (err error) {
	for name, key := range keys {
		if err = key.compile(name); err != nil {
			return fmt.Errorf("failed to compile %s: %s", name, err)
		}
	}

	for nameNum, names := 0, maps.Keys(keys); nameNum < len(names)-1; nameNum++ {
	_loop:
		for _, name := range names[nameNum+1:] {
			keyA, keyB := func() (*Key, *Key) {
				var (
					keyA = keys[names[nameNum]]
					keyB = keys[name]
				)

				if keyA.Len() < keys[name].Len() {
					return keyB, keyA
				}

				return keyA, keyB
			}()

			for pairNum := range keyB.Code {
				if !bytes.HasPrefix(keyA.Code[pairNum], keyB.Code[pairNum]) {
					continue _loop
				}
			}

			return fmt.Errorf("%s and %s overlap each other", names[nameNum], name)
		}
	}

	return
}

// Return the pointer to the pressed keys.
func (keys Keys) PressedKeys() *PressedKeys {
	var names = PressedKeys(maps.Keys(keys))

	return &names
}
